package com.example.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.AirQualitySensor;
import com.example.entity.FlameSensor;
import com.example.entity.LightSensor;
import com.example.entity.Params;
import com.example.repository.LightSensorMapper;
import com.example.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class LightSensorService extends ServiceImpl<LightSensorMapper, LightSensor> {

    @Resource
    private LightSensorMapper lightSensorMapper;


    public PageInfo<LightSensor> getSensorData(Params params){
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<LightSensor> search = lightSensorMapper.getSensorData();
        return PageInfo.of(search);
    }

    public double getLightIntensity() {
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MINUTE, -20);
        Date twentySecondsAgo = calendar.getTime();
        return lightSensorMapper.selectList(Wrappers.<LightSensor>lambdaQuery().between(
                        LightSensor::getCreateTime, DateUtil.date2Str(twentySecondsAgo), DateUtil.date2Str(now)))
                .stream().mapToInt(LightSensor::getLightIntensity).average().orElse(0);
    }


    public void addLS(LightSensor lightSensor) {
        lightSensorMapper.insert(lightSensor);
    }

    public void deleteLS(Long id) {
        lightSensorMapper.deleteById(id);
    }

    public Map<String, Object> initLine(Params params) {

        List<Map<String, Object>> rawList = lightSensorMapper.initLine(params);
        // 固定时间段（x轴）
        List<String> xAxis = generateXAxis(params.getInterval());
        List<Integer> yAxis = new ArrayList<>(Collections.nCopies(xAxis.size(), 0));  // 默认全部为0
        // 建立时间段与索引映射
        Map<String, Integer> indexMap = new HashMap<>();
        for (int i = 0; i < xAxis.size(); i++) {
            indexMap.put(xAxis.get(i), i);
        }
        // 用返回结果更新对应位置的值
        for (Map<String, Object> row : rawList) {
            String timeGroup = (String) row.get("time_group");
            Number avg = (Number) row.get("avg_light");
            int value = (avg != null) ? (int) Math.floor(avg.doubleValue()) : 0;
            Integer idx = indexMap.get(timeGroup);
            if (idx != null) {
                yAxis.set(idx, value);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", xAxis);
        result.put("yAxis", yAxis);
        return result;
    }
    // 补充生成xAxis的方法
    private List<String> generateXAxis(int interval) {
        List<String> xAxis = new ArrayList<>();
        for (int i = 0; i < 24; i += interval) {
            xAxis.add(String.format("%02d:00", i));
        }
        xAxis.add("24:00"); // 补上24:00作为最后一个点
        return xAxis;
    }

    public Map<String, Object> initLineForAdmin(Params params) {

        List<Map<String, Object>> rawList = lightSensorMapper.initLineForAdmin(params);
        // 调用封装的方法
        List<String> dateLabels = generateLastNDaysLabels(params.getPast());
        List<Integer> lightList = new ArrayList<>(Collections.nCopies(dateLabels.size(), 0));
        Map<String, Integer> dateIndexMap = new HashMap<>();
        for (int i = 0; i < dateLabels.size(); i++) {
            dateIndexMap.put(dateLabels.get(i), i);
        }
        for (Map<String, Object> row : rawList) {
            String date = String.valueOf(row.get("date"));
            Integer light = ((Number) row.get("avg_light")).intValue();
            Integer idx = dateIndexMap.get(date);
            if (idx != null) {
                lightList.set(idx, light);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", dateLabels);
        result.put("yAxis", lightList);
        return result;
    }

    private List<String> generateLastNDaysLabels(int n) {
        List<String> dateLabels = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = n - 1; i >= 0; i--) {
            cal.setTime(new Date());
            cal.add(Calendar.DAY_OF_MONTH, -i);
            dateLabels.add(sdf.format(cal.getTime()));
        }
        return dateLabels;
    }
}
